﻿using System;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace UpdateApp.Config
{
    internal static class Helper
    {
        /// <summary>
        /// 是否需要更新，ture更新，false不更新; version1主动与version2比较
        /// </summary>
        /// <param name="version1">比较版本号</param>
        /// <param name="version2">被比较版本号</param>
        public static bool IsUpdate(this string? version1, string? version2)
        {
            try
            {
                var split1 = version1?.Split('.');
                var split2 = version2?.Split(".");
                var length = split1!.Length > split2!.Length ? split2!.Length : split1!.Length;
                for (int i = 0; i < length; i++)
                    if (int.Parse(split1![i]) < int.Parse(split2![i]))
                        return true;
            }
            catch { }

            return false;
        }

        /// <summary>
        /// 获取程序文件版本号
        /// </summary>
        /// <param name="appName">程序名称，例如 eson.exe</param>
        public static string GetFileVersion(string? appName)
        {
            if (string.IsNullOrWhiteSpace(appName))
                return "0";
            try
            {
                var fileVersion = FileVersionInfo.GetVersionInfo(Path.Combine(AppContext.BaseDirectory, appName));
                return fileVersion.FileVersion ?? "0";
            }
            catch
            {
                return "0";
            }
        }

        /// <summary>
        /// Config配置到VersionDto信息
        /// </summary>
        public static VersionDto MapTo(this Config config)
        {
            return new VersionDto
            {
                UpdateApp = config.UpdateApp,
                UpdateMethod = config.MethodType,
                UpdateUrl = config.DownloadUrl,
                AppKey = config.UpdateApp,
                Version = config.Version
            };
        }

        /// <summary>
        /// http get 获取版本相关信息
        /// </summary>
        /// <param name="versionUrl">版本URL</param>
        public static async Task<VersionDto?> GetVersionAsync(this string? versionUrl)
        {
            if (string.IsNullOrEmpty(versionUrl))
                return null;
            try
            {
                using var client = new HttpClient();
                return await client.GetFromJsonAsync<VersionDto>(versionUrl);
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 异常框
        /// </summary>
        public static void ShowError(this Exception e, Window? owner = null)
        {
            var msg = $"{e?.Message}{Environment.NewLine}{e?.StackTrace}";
            Application.Current.Dispatcher.Invoke(() =>
            {
                if (owner != null)
                    MessageBox.Show(owner, msg, "", MessageBoxButton.OK, MessageBoxImage.Error);
                else
                    MessageBox.Show(msg, "", MessageBoxButton.OK, MessageBoxImage.Error);
            });
        }

        /// <summary>
        /// 提示框
        /// </summary>
        public static void ShowInfo(this string msg, Window? owner = null)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                if (owner != null)
                    MessageBox.Show(owner, msg, "", MessageBoxButton.OK, MessageBoxImage.Information);
                else
                    MessageBox.Show(msg, "", MessageBoxButton.OK, MessageBoxImage.Information);
            });
        }
    }
}
